﻿using Aliyun.OpenServices;
using Aliyun.OpenServices.OpenStorageService;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Novel.Collection
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            RichTextBox.CheckForIllegalCrossThreadCalls = false;
            
        }
        Thread thread = null;
        ClientConfiguration clientConfig = new ClientConfiguration();
        ObjectMetadata metadata = new ObjectMetadata();
        private void btnStartCoolection_Click(object sender, EventArgs e)
        {
            try
            {
                Constant.SID = int.Parse(tbStartCoolectionID.Text.Trim());
                Constant.EID = int.Parse(tbendCoolectionID.Text.Trim());
                if (Constant.EID < Constant.SID) { MessageBox.Show("结束ID不能小于开始ID"); return; }
            }
            catch { MessageBox.Show("开始或结束id错误"); return; }
            Constant.sqlConnStr = "Data Source=" + tbSqlHost.Text.Trim() + ";Initial Catalog=" + tbSqlName.Text.Trim() + ";Persist Security Info=True;User ID=" + tbSqlUser.Text.Trim() + ";Password=" + tbSqlPasswd.Text.Trim() ;
            tabControl1.SelectedIndex = 2;
            thread = new Thread(Strat);
            thread.IsBackground = true;
            thread.Start();
        }
        Sys.BLL.novel_article bll_art = new Sys.BLL.novel_article();
        Sys.BLL.novel_chapter bll_chap = new Sys.BLL.novel_chapter();
        private string novelName,novelAuthor;
        private void Strat()
        {
            for (int ID = Constant.SID; ID < Constant.EID+1; ID++)
            {
                WriteLog("开始采集【" + ID + "】.......\n");
                Sys.Model.novel_article model_art = new Sys.Model.novel_article();
                model_art=RegexData.CooleArt(NetServer.Get("http://www.qingdi.com/book/" + ID + ".html"));
                int Aid = 0;
                if (model_art != null) { WriteLog("\n\n采集到小说【"+model_art.Title+"】，作者【"+model_art.Author+"】\n"); }
                if (bll_art.Exists(model_art.Title, model_art.Author)) { /*已存在小说,获取小说id*/ Aid = bll_art.GetID(model_art.Title, model_art.Author); WriteLog("小说【" + model_art.Title + "】，作者【" + model_art.Author + "】已存在\n"); }
                else {

                    Aid = bll_art.Add(model_art);
                        model_art.ID = Aid;
                        if (!bll_art.ExistsCover(Aid))
                        {
                            object obj = (object)model_art;
                            Thread t = new Thread(UploadCover);
                            t.IsBackground = true;
                            t.Start(obj);
                        }
                    WriteLog("小说【" + model_art.Title + "】，作者【" + model_art.Author + "】成功添加到数据库中\n");
                }//添加小说

                if (Aid > 0)
                {
                    Dictionary<string, string> list = new Dictionary<string, string>();
                    list = RegexData.CooleChapter(NetServer.Get(model_art.InfoUrl));
                    string url = model_art.InfoUrl.Replace("index.html", "");
                    url = url.Replace("/html/", "/txt/");
                    if (list != null) { WriteLog("当前采集ID【" + ID + "】小说【" + model_art.Title + "】，作者【" + model_art.Author + "】采集了【" + list.Count + "】章\n"); }
                    foreach (KeyValuePair<string, string> item in list)
                    {
                        
                        int chaptrID;
                        
                        Sys.Model.novel_chapter model_chap = new Sys.Model.novel_chapter();
                        chaptrID=bll_chap.GetCount(Aid)+1;
                        model_chap.Aid = Aid;
                        model_chap.Chaptername = item.Value;//本章标题
                        model_chap.Chapternum = chaptrID;//章ID
                        model_chap.Created = DateTime.Now;
                        model_chap.Isvip = 0;
                        model_chap.Modified = DateTime.Now;
                        model_chap.Price = 0;
                        model_chap.Size = 0;
                        model_chap.Status = 1;
                        model_chap.Articlepath = url + item.Key + ".txt";
                        model_chap.CollectionMark = item.Key.Trim();
                            if (!bll_chap.Exists(Aid, model_chap.Chaptername, item.Key.Trim()))
                            {
                                int chaptrNum;
                                novelName = model_art.Title;
                                novelAuthor = model_art.Author;
                                chaptrNum = bll_chap.Add(model_chap);
                                if (checkBox1.Checked)
                                {

                                    model_chap.ID = chaptrNum;
                                    object obj = (object)model_chap;
                                    Thread t = new Thread(UploadChapter);
                                    t.IsBackground = true;
                                    t.Start(obj);
                                }

                                WriteLog("当前采集ID【" + ID + "】小说【" + model_art.Title + "】，作者【" + model_art.Author + "】【" + item.Value + "】成功添加到数据库\n");
                            }
                            else { WriteLog("当前采集ID【" + ID + "】小说【" + model_art.Title + "】，作者【" + model_art.Author + "】【" + item.Value + "】已存在\n"); }
                    }
                }
            }
        }


        private void WriteLog(string Log)
        {
            try
            {
                try
                {
                    tbCoolectionLog.AppendText(Log);
                }
                catch { }
            }
            catch (Exception e)
            {
                AdinZ.Common.WriteLog write = new AdinZ.Common.WriteLog("log/log.log");
                write.WriteLine(Log+"\r\n" + e + "\r\n\r\n");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Download df = new Download();
            df.Show();
        }



        private void UploadCover(object obj)
        {
            Sys.Model.novel_article model = (Sys.Model.novel_article)obj;
            AdinZ.Common.DownloadFile downloadCover = new AdinZ.Common.DownloadFile();
            downloadCover.StrFileName = "cover/cover_" + model.ID + ".jpg";
            downloadCover.StrUrl = model.Cover;
            if (downloadCover.Download())
            {

                try
                {
                    using (var fs = File.Open(downloadCover.StrFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite))
                    {
                        metadata.ContentType = "image/jpeg";
                        if (AdinZ.Common.OssUpload.Upload(downloadCover.StrFileName, fs, metadata, clientConfig))
                        {
                            if (bll_art.UpdateCover(model.ID, downloadCover.StrFileName, 1) > 0)
                                WriteLog("小说【" + model.Title + "】，作者【" + model.Author + "】封面已经成功上传到OSS服务器中"+downloadCover.StrFileName+".\n");
                        }
                    }
                    File.Delete(downloadCover.StrFileName);
                }
                catch (Exception e)
                {
                    AdinZ.Common.WriteLog write = new AdinZ.Common.WriteLog("log/log.log");
                    write.WriteLine("出错了错误章节ID" + model.ID + "错误日志:" + e + "\r\n\r\n");
                }

            }
        }

        private void UploadChapter(object obj)
        {
            Sys.Model.novel_chapter model = (Sys.Model.novel_chapter)obj;
            AdinZ.Common.DownloadFile download = new AdinZ.Common.DownloadFile();
            download.StrFileName = "chapter/" + model.ID + ".txt";
            download.StrUrl = model.Articlepath;
            if (download.Download())
            {
                string str = File.ReadAllText(download.StrFileName, Encoding.Default); //获得整个文本
                str = "\t" + model.Chaptername + "\r\n\r\n" + str;
                try
                {
                    using (var fs = File.Open(download.StrFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite))
                    {
                        metadata.ContentType = "text/plain";
                        if (AdinZ.Common.OssUpload.Upload(download.StrFileName, fs, metadata, clientConfig))
                        {
                            if (bll_chap.UpdateChapterPath(model.ID, download.StrFileName, 1,download.lDownloadFile) > 0)
                                WriteLog("小说【" + novelName + "】，作者【" + novelAuthor + "】【" + model.Chaptername + "】已经成功上传到OSS服务器中" + download.StrFileName + ".\n");
                        }
                    }
                    File.Delete(download.StrFileName);
                }
                catch (Exception e)
                {
                    AdinZ.Common.WriteLog write = new AdinZ.Common.WriteLog("log/log.log");
                    write.WriteLine("出错了错误章节ID" + model.ID + "错误日志:" + e + "\r\n\r\n");
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }

    }
}
